﻿using System;
using System.Collections.Generic;
using System.Threading;
using Bookvar.ObjectModel;
using Bookvar.Web.LiveServices;

namespace Bookvar.Web
{
    public static class LiveService
    {
        public static IEnumerable<ImageInfo> GetImages( string searchTerm, int imagesCount )
        {
            using ( var proxy = new MSNSearchPortTypeClient() )
            {
                var searchRequest = new SearchRequest();

                SourceRequest[] sr = new SourceRequest[1];
                sr[ 0 ] = new SourceRequest();
                sr[ 0 ].Source = SourceType.Image;
                sr[ 0 ].ResultFields = ResultFieldMask.Description | ResultFieldMask.Image | ResultFieldMask.Title;
                sr[ 0 ].Count = imagesCount;

                searchRequest.Query = searchTerm;
                searchRequest.Requests = sr;

                searchRequest.AppID = "	7B2D878864A59E996BF8CF8D60800D98661B66F3";
                searchRequest.CultureInfo = Thread.CurrentThread.CurrentUICulture.Name;

                SearchResponse searchResponse = proxy.Search( searchRequest );
                var images = new List<ImageInfo>( searchResponse.Responses[ 0 ].Results.Length );
                foreach ( Result sourceResult in searchResponse.Responses[ 0 ].Results )
                {
                    images.Add( new ImageInfo( new Uri( sourceResult.Image.ImageURL ),
                                               new Uri( sourceResult.Image.ThumbnailURL ), sourceResult.Title,
                                               sourceResult.Description, sourceResult.Image.ImageWidth,
                                               sourceResult.Image.ImageHeight ) );
                }
                return images;
            }
        }
    }
}
